/**
 *  2018-6-23
 *  email:nur01@qq.com
 */
import React from 'react'
import {AsyncStorage} from 'react-native'
import CryptoJS from 'crypto-js';

export const SERVER_TYPE = {
    admin: 'https://user.iparbio.com/api/v3/',
    centerIpar: 'https://center.iparbio.com/',
    logistics: 'https://logistics.iparbio.com/',
    adminIpar: 'https://admin.iparbio.com/api/v3/',
    goods: 'https://goods.iparbio.com/api/v1/',
    synPays: 'https://api.synpays.com/v2/Partner/',
    article: 'https://article.iparbio.com/api/',
    uiAdminIpar: 'https://img.iparbio.com/app/',
    invoice: 'http://admin.iparbio.com/invoice?',
    payServer: 'https://admin.iparbio.com/',
    imgIpar: 'https://img.iparbio.com/',
};

export const SynpaysTeken = 'Basic aXBhcmJpbzpzeW5wYXlz';

export const IMAGE_URL = 'https:';

export default class IparNetwork {


    timeout(timeout) {
        return new Promise((resolve, reject) => {
            setTimeout(function () {
                reject(new Error('time out !'))
            }, timeout || 40000);
        });
    }

    getM() {
        let charactors = "1234567890";
        let value = '', i;
        for (j = 1; j <= 4; j++) {
            i = parseInt(10 * Math.random());
            value = value + charactors.charAt(i);
        }
        return value;
    }

    getAccept() {
        let m1 = this.getM();
        let m2 = this.getM();
        let m3 = this.getM();
        let m4 = this.getM();
        return {dom: Encrypt(m2 + '/8NONwyJtHesysWpM/8855567898882222/' + m3), time: m1 + m2 + m3 + m4};
    }


    /**
     * 网络请求GET
     * @param serverType 服务器地址
     * @param params
     * @param token
     * @returns {Promise<any>}
     */
    getRequest(serverType, params, token, timeout) {
        let accept = this.getAccept();

        const fetchOptions = {
            method: 'GET',
            headers: {
                'Authorization': token,
                'Accept-Dom': accept.dom,
                'Accept-time': accept.time,
                "Connection": "close",
            },
        };

        console.log(serverType + params);
        console.log(fetchOptions);
        return new Promise((resolve, reject) => {
            fetch(serverType + params, fetchOptions)
                .then((response) => response.json())
                .then((result) => {
                    console.log(result);
                    resolve(result)
                })
                .catch((error) => {
                    reject(error);
                });

            this.timeout(timeout).catch((error) => {
                reject(error);
            })
        })
    }


    /**
     * 获取本地数据
     * @param url
     * @param date 过去的时间
     */
    getAsyncData(url, date) {
        return new Promise((resolve, reject) => {
            this.fetchLocalData(url)
                .then((result) => {
                    if (result && this.checkData(result.update_date, date)) {
                        resolve(result);
                    } else {
                        this.removeData(url);
                        reject(new Error('data null'));
                    }
                })
                .catch((error) => {
                    reject(error);
                })
        });
    }


    /**
     * 是否过去时间
     */
    checkData(date, time) {
        let newDate = new Date();
        let oldDate = new Date();
        oldDate.setTime(date);
        if (oldDate.getMonth() !== newDate.getMonth()) return false;
        return oldDate.getDate() - newDate.getDate() <= time;
    }

    /**
     * 获取本地数据
     */
    fetchLocalData(url) {
        return new Promise((resolve, reject) => {
            AsyncStorage.getItem(url, (error, result) => {
                if (!error) {
                    try {
                        resolve(JSON.parse(result));
                    } catch (e) {
                        reject(e);
                        console.error(e);
                    }
                } else {
                    reject(error);
                    console.error(error);
                }
            })
        });
    }


    /**
     * 缓存到本地
     * @param url
     * @param data
     * @param callback
     */
    saveData(url, data, callback) {
        if (!data || !url) return;
        let wrapData = {data: data, update_date: new Date().getTime()};
        AsyncStorage.setItem(url, JSON.stringify(wrapData), callback);

    }

    /**
     * 删除本地的数据
     * @param url
     * @param data
     * @param callback
     */
    removeData(url, callback) {
        if (!data || !url) return;
        AsyncStorage.removeItem(url, callback)
    }


    /**
     * 网络请求post
     *url :请求地址
     *data:参数
     *callback:回调函数
     */
    getPostFrom(serverType, fromData, token) {
        let accept = this.getAccept();

        const fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Authorization': token,
                'Accept-Dom': accept.dom,
                'Accept-time': accept.time,
                "Connection": "close",
            },
            body: fromData,//这里我参数只有一个data,大家可以还有更多的参数 'data=' + data + ''

        };
        console.log(serverType, fetchOptions);
        return new Promise((resolve, reject) => {
            fetch(serverType, fetchOptions)
                .then((response) => response.json())
                .then((result) => {
                    console.log(result);
                    resolve(result)
                })
                .catch((error) => {
                    reject(error)
                });
            this.timeout().catch((error) => {
                reject(error);
            })
        });

    }

    /**
     * 网络请求post JSON
     *SERVER_TYPE :请求地址
     *data:参数(Json对象)
     *callback:回调函数
     */
    getPostJson(serverType, data, token) {


        let accept = this.getAccept();
        const fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                //json形式
                'Content-Type': 'application/json',
                'Authorization': token,
                'Accept-Dom': accept.dom,
                'Accept-time': accept.time,
                "Connection": "close",
            },
            body: JSON.stringify(data),
        };
        console.log(serverType, fetchOptions);

        return new Promise((resolve, reject) => {
            fetch(serverType, fetchOptions)
                .then((response) => response.json())
                .then((result) => {
                    resolve(result)
                })
                .catch((error) => {
                    reject(error)
                });
            this.timeout().catch((error) => {
                reject(error);
            })
        })

    }

}


/**
 * type===1 =>auth
 * @param country
 * @param type
 * @returns {string}
 */
export function getSynPaysSellerAuth(country, type) {

    let auth = '';
    let seller = '';

    if (country === "KZ") {
        auth = '5833b940534841e08ee425673ae1191f';
        seller = '201709010000292';
    } else if (country === "KG") {
        auth = 'f6a3b08e243f457d9c8216c29321a49f';
        seller = '201709010000293';
    } else if (country === "UZ") {
        auth = '63052399e9764397b9c2e4c7e32c724d';
        seller = '201709010000294';
    } else if (country === "US") {
        auth = '3eb5509a70dc47aeb9c3777da5638fe3';
        seller = '201709010000295';
    } else if (country === "RU") {
        auth = '700edf6dbea148f893f3d87bfef0eef8';
        seller = '201709010000296';
    } else if (country === "AZ") {
        auth = '3837dfbefa194386b6833801465215ac';
        seller = '201709010000297';
    } else if (country === "TJ") {
        auth = '36d9090b0cc04e8b9c8548c1db4c5507';
        seller = '201709010000298';
    } else if (country === "MN") {
        auth = '3492aca4edc141648accc56047d839bf';
        seller = '201709010000299';
    } else if (country === "AR") {
        auth = '17ae1ead900f4b77916d6b2d34674dcd';
        seller = '201709010000300';
    } else if (country === "IN") {
        auth = 'f6deaa9417984a7c96a3d411b328adc2';
        seller = '201709010000301';
    } else if (country === "TR") {
        auth = '03bd41d1f3ae48a297446f85b63fc4c0';
        seller = '201709010000302';
    } else if (country === "ID") {
        auth = '204339ba265e4c68be68feaa779518a3';
        seller = '201709010000303';
    } else if (country === "MY") {
        auth = 'f79dd20c13d84e3db8b200e5c4ccdca0';
        seller = '201709010000304';
    } else if (country === "DE") {
        auth = '3eb5509a70dc47aeb9c3777da5638fe3';
        seller = '201709010000305';
    } else if (country === "BY") {
        auth = 'f1a2e36513514cca8b2cf15c3c1636e4';
        seller = '201709010000306';
    } else {
        auth = 'bd6dbd063f5ab7394879e3c08781cd72';
        seller = '201709010000291';
    }

    return type === 1 ? auth : seller
}

/*AES加密*/
/**
 * @return {string}
 */
export function Encrypt(data) {
    // let dataStr = JSON.stringify(data);
    let encrypted = CryptoJS.AES.encrypt(data, CryptoJS.enc.Latin1.parse('8855567898882222'), {
        iv: CryptoJS.enc.Latin1.parse('8NONwyJtHesysWpM'),
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
}
